import React, { useState, useEffect } from 'react';
import { Box, Text } from 'ink';
import { ConnectionStatus, ThemeConfig, InterruptStatus } from '../types';
import { mcpManager } from '../services/mcpManager';

interface StatusBarProps {
  connectionStatus: ConnectionStatus;
  isLoading: boolean;
  theme: ThemeConfig;
  interruptStatus?: InterruptStatus;
  showMCPStatus?: boolean;
}

const StatusBar: React.FC<StatusBarProps> = ({ 
  connectionStatus, 
  isLoading, 
  theme,
  interruptStatus,
  showMCPStatus = true
}) => {
  const [mcpServersCount, setMcpServersCount] = useState(0);
  const [mcpToolsCount, setMcpToolsCount] = useState(0);

  useEffect(() => {
    // 更新MCP服务器状态
    const updateMCPStatus = () => {
      const servers = mcpManager.getAllServers();
      const runningServers = servers.filter(s => s.status === 'running');
      const availableTools = mcpManager.getAvailableTools();
      
      setMcpServersCount(runningServers.length);
      setMcpToolsCount(availableTools.length);
    };

    // 初始更新
    updateMCPStatus();

    // 定期更新MCP状态（5秒间隔）
    const interval = setInterval(updateMCPStatus, 5000);

    return () => clearInterval(interval);
  }, []);
  const getStatusText = () => {
    if (interruptStatus?.isInterrupting) return '⏹️ 正在中断...';
    if (isLoading) return '🔄 正在处理...';
    if (connectionStatus.retrying) return '🔄 重新连接中...';
    if (!connectionStatus.connected) {
      return `❌ 连接失败${connectionStatus.error ? `: ${connectionStatus.error}` : ''}`;
    }
    return '✅ 已连接';
  };

  const getMCPStatusText = () => {
    if (!showMCPStatus) return '';
    if (mcpServersCount === 0) return 'MCP: 无服务器';
    return `MCP: ${mcpServersCount}服务器 ${mcpToolsCount}工具`;
  };

  const getMCPStatusColor = () => {
    if (mcpServersCount === 0) return 'gray';
    return 'cyan';
  };

  const getStatusColor = () => {
    if (interruptStatus?.isInterrupting) return 'yellow';
    if (isLoading || connectionStatus.retrying) return theme.systemMessage;
    if (!connectionStatus.connected) return theme.errorMessage;
    return 'green';
  };

  return (
    <Box paddingX={1} paddingY={1}>
      <Box flexGrow={1}>
        <Text color={getStatusColor()}>
          {getStatusText()}
        </Text>
        {showMCPStatus && mcpServersCount > 0 && (
          <Text color={getMCPStatusColor()} dimColor>
            {' | '}{getMCPStatusText()}
          </Text>
        )}
      </Box>
      
      <Box>
        <Text color="gray" dimColor>
          Ctrl+C: 退出 | Ctrl+L: 清屏 | ESC: 中断 | Enter: 发送
        </Text>
      </Box>
    </Box>
  );
};

export default StatusBar;